import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:example_example/bean/BaseBean.dart';
import 'package:example_example/bean/BossBean.dart';
import 'package:example_example/pages/person/ChangeCode.dart';
import 'package:example_example/services/ScreenAdapter.dart';
import 'package:jpush_flutter/jpush_flutter.dart';

import '../../pages/person/Login.dart';
import '../../util/ToastUtils.dart';

import '../../global/Global.dart';
import '../../util/HttpUtil.dart';
import '../../util/LogUtil.dart';

import '../../util/Storage.dart';

import '../../global/GlobalUrl.dart';
import 'package:flutter/material.dart';
import '../../YColors.dart';
import '../../pages/view/HeaderView.dart';
import '../../services/TLSizeFit.dart';
import '../../pages/view/NoDataView.dart';
import '../../pages/view/ErrorView.dart';

/**
 *  设计图样式的----我的待办
 */
class MyNeedDoPage extends StatefulWidget {
  MyNeedDoPage({Key key}) : super(key: key);

  _MyNeedDoPageState createState() => _MyNeedDoPageState();
}

class _MyNeedDoPageState extends State<MyNeedDoPage> {
  List tabList = [];
  bool hasMore = true; //判断有没有数据
  List imageList = [
    "images/daibanrengwu.png",
    "images/lishirengwu.png",
    "images/banjierengwu.png",
    "images/wofaqide.png",
    "images/daibanrengwu.png",
    "images/lishirengwu.png",
    "images/banjierengwu.png",
    "images/wofaqide.png",
    "images/daibanrengwu.png",
    "images/lishirengwu.png",
    "images/banjierengwu.png",
    "images/wofaqide.png"
  ];

  bool noDataflag = false;
  bool errorFlag = false;

  String Rid = "";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print("我的待办。。。initState");
    this.initJpush();
//    var context=this.context;
    getMenuData();
//    initHttpData();
    this.setCheckInfor();
  }

  initJpush() async {
    LogUtil.v("初始化极光推送的功能");
    var id = await Storage.getId(); //注意必须要用 await来修饰
    LogUtil.v("获取登录的id:$id");

    JPush jpush = new JPush();
    //获取注册的id
    jpush.getRegistrationID().then((rid) {
      print("获取注册的RegistrationID:$rid");

      httpJPushRegistrationID(rid);
    });

    //初始化
//    插件版本 >= 0.0.8 android 端支持在 setup 方法中动态设置 channel，动态设置的 channel 优先级比 manifestPlaceholders 中的 JPUSH_CHANNEL 优先级要高。
    jpush.setup(
      appKey: "5d3f34bc7315e47e68864935",
      channel: "theChannel",
      production: false,
      debug: true, // 设置是否打印 debug 日志
    );

    //设置别名  实现指定用户推送
//    jpush.setAlias(id).then((map) {
////      print("设置别名成功了哈222：$id");
////      ToastUtils.toast("设置别名成功");
////      ToastUtils.toast("设置别名成功了哈222：$id");
//    });

//    申请推送权限，注意这个方法只会向用户弹出一次推送权限请求（如果用户不同意，之后只能用户到设置页面里面勾选相应权限），需要开发者选择合适的时机调用。
    jpush.applyPushAuthority(
        new NotificationSettingsIOS(sound: true, alert: true, badge: true));

    jpush.setup(
      debug: false, // 设置是否打印 debug 日志
    );

    try {
      //监听消息通知
      jpush.addEventHandler(
        // 接收通知回调方法。
        onReceiveNotification: (Map<String, dynamic> message) async {
          print("flutter onReceiveNotification: $message");
        },
        // 点击通知回调方法。
        onOpenNotification: (Map<String, dynamic> message) async {
          print("flutter onOpenNotification: $message");
        },
        // 接收自定义消息回调方法。
        onReceiveMessage: (Map<String, dynamic> message) async {
          print("flutter onReceiveMessage: $message");
        },
      );
    } catch (e) {
      print('极光sdk配置异常');
    }
  }

  @override
  Widget build(BuildContext context) {
    TLSizeFit.initialize();
    ScreenAdapter.init(context);
    print("我的待办。。。build");

    // TODO: implement build
    return Scaffold(
      appBar: HeaderView(
        title: "我的待办",
        isShowReturnArrow: false,
      ),
      body: Container(
        color: YColors.orderBackground,
        padding: EdgeInsets.fromLTRB(
            TLSizeFit.setPx(20), TLSizeFit.setPx(20), TLSizeFit.setPx(20), 0),
        child: setBodyView(),
      ),
    );
  }

  /**
   * 接口获取数据
   */
  initHttpData() async {
    String apiUrlhttp = GlobalUrl.LISTPERMISSION;
    var map = {
      "": "",
    };
    String access_token = await Storage.getToken();
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };
    HttpUtil.get(apiUrlhttp,
        context: this.context, data: map, headers: mapHeaders, success: (data) {
      var success = data["success"];
//      LogUtil.v("success:$success");
      var message = data["msg"];
      var body = data["data"];
      var code = data["code"];
//      LogUtil.v("body:$body");
      if (success != null && success == true) {
        LogUtil.v("进来了");
        Storage.setString(Global.MENUDATA, json.encode(body));

        List menuList = body["menuList"];
//        LogUtil.v("menuList:menuList");
        LogUtil.v(menuList.length);

        setMenuData(menuList);

//        for (var i = 0; i < menuList.length; i++) {
//          var miName = menuList[i]["miName"];
//          LogUtil.v("一级数据miName:$miName");
////          tabList.add(miName); // 一级数据
//          if (miName != null && miName == "待办管理") {
//            // 添加待办管理的数据
//            List children = menuList[i]["children"];
//            for (var j = 0; j < children.length; j++) {
//              var name = children[j]["miName"];
////
//              tabList.add(name); // 一级数据
//              LogUtil.v("二级数据name:$name");
//            }
//          }
//
//          List children = menuList[i]["children"];
//          if (children != null) {
////            for (var i = 0; i < children.length; i++) {
////              var name = children[i]["miName"];
////              LogUtil.v("name:$name");
////            }
//          }
//        }

//        setState(() {
//          tabList = tabList;
//        });
//        if (tabList.length == 0) {
//          setState(() {
//            noDataflag = true;
//          });
//        } else {
//          setState(() {
//            tabList = tabList;
//            noDataflag = false;
//          });
//        }
//        setState(() {
//          this.hasMore = false;
//        });
      } else {
        setState(() {
          this.hasMore = false;
        });
        if (message != null) {
          ToastUtils.toast(message);
        }
        if (code == "401") {
          //用户登录超时
          print("超时了啊");
          Storage.clear(); // 清除数据
          //跳转并关闭当前页面
          Navigator.pushAndRemoveUntil(
            context,
            new MaterialPageRoute(builder: (context) => new LoginPage()),
            (route) => route == null,
          );
        }
      }
    }, error: (errorMsg) {
      print("首页的接口报错了");
      setState(() {
        errorFlag = true;
      });
    });
  }

  setMenuData(List menuList) {
    for (var i = 0; i < menuList.length; i++) {
      var miName = menuList[i]["miName"];
      LogUtil.v("一级数据miName:$miName");
//          tabList.add(miName); // 一级数据
      if (miName != null && miName == "待办管理") {
        // 添加待办管理的数据
        List children = menuList[i]["children"];
        for (var j = 0; j < children.length; j++) {
          var name = children[j]["miName"];
//
          tabList.add(name); // 一级数据
          LogUtil.v("二级数据name:$name");
        }
      }

      List children = menuList[i]["children"];
      if (children != null) {
//            for (var i = 0; i < children.length; i++) {
//              var name = children[i]["miName"];
//              LogUtil.v("name:$name");
//            }
      }
    }

    if (tabList.length == 0) {
      setState(() {
        noDataflag = true;
      });
    } else {
      setState(() {
        tabList = tabList;
        noDataflag = false;
      });
    }
    setState(() {
      this.hasMore = false;
    });
  }

  getMenuData() async {
    String menu = await Storage.getString(Global.MENUDATA);
//    LogUtil.v("二级数据menu:$menu");
//    LogUtil.v("二级数据menuList:$menuList");
    if (menu != null && menu != '') {
      var menuData = json.decode(menu);
      List menuList = menuData["menuList"];
      setMenuData(menuList);
    } else {
      initHttpData();
    }
  }

  setCheckInfor() async {
    String id = await Storage.getId();
    String apiUrlhttp = GlobalUrl.CHECKPASSWORD + "?id=" + id;
//    var map = {
//      "id": id,
//    };
    var access_token = await Storage.getToken() ;
    LogUtil.v("进来了access_token:" + access_token);

    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };
    var dio = Dio();

    dio.options.headers.addAll(mapHeaders); // 添加headers,如需设置统一的headers信息也可在此添加
    Response response = await dio.get(apiUrlhttp);
    LogUtil.v("进来了data:" + response.data.toString());
//       var str = json.encode(response.data);
    var jsonMap = BossBean.fromJson(response.data);
    String result = jsonMap.code;
    String message = jsonMap.msg;
    bool success = jsonMap.success;
    var getData = jsonMap.data;
    LogUtil.v("进来了getData:" + getData);

    if (success) {
      if ( getData!=null && getData == "1") {
        LogUtil.v("不用任何操作。。");

      } else {
//    传入用户id，返回状态值：1正常；21默认密码未修改；22密码过期；
        LogUtil.v("去修改密码。。");
//        if (getData == 21) {
//          ToastUtils.toast("默认密码未修改,请修改密码");
//        } else if (getData == 22) {
//          ToastUtils.toast("密码过期,请修改密码");
//        }
//        Navigator.pop(context);
//        Navigator.pushNamed(
//            context, "/ChangeCodePage",arguments: {Global.FLAG: "force",Global.CHANGECODESTATE: getData}); //, arguments: {Global.FLAG: "111"}

        Map arguments ={Global.FLAG: "force",Global.CHANGECODESTATE: getData};
        Navigator.pushAndRemoveUntil(
          context,
          new MaterialPageRoute(builder: (context) => new ChangeCodePage(arguments:arguments)),
              (route) => route == null,
        );
      }
//      Navigator.pop(context);
//      Navigator.pushNamed(
//          context, "/ChangeCodePage",arguments: {Global.FLAG: "force"});

    } else {
      ToastUtils.toast(message);
    }

//    HttpUtil.get(apiUrlhttp, data: map, headers: mapHeaders, success: (data) {
//      LogUtil.v("进来了data:" + data);
////      进来了data:{code: 200, success: true, data: 21, msg: 操作成功}
//      var jsonMap = BossBean.fromJson(data);
//      String result = jsonMap.code;
//      String message = jsonMap.msg;
//      bool success = jsonMap.success;
//      var getData = jsonMap.data;
//      if(success){
//        if(getData!=null && getData==1){
//          //跳转并关闭当前页面
//        Navigator.pushAndRemoveUntil(
//          context,
//          new MaterialPageRoute(builder: (context) => new Tabs()),
//          (route) => route == null,
//        );
//
//        }else{
//          Navigator.pushNamed(context, "/ChangeCodePage", arguments: {Global.FLAG: getData});
//        }
//      }else{
//        ToastUtils.toast(message);
//      }
//
//
//
//    }, error: (errorMsg) {});
  }

  Widget setBodyView() {
    return Stack(
      children: <Widget>[
        (this.tabList.length > 0 && !noDataflag)
            ? GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisSpacing: TLSizeFit.setPx(20), // 水平 Widge间距
                  mainAxisSpacing: TLSizeFit.setPx(15), // 垂直的Widge 间距
                  childAspectRatio: 1.9, //宽度和高度的比例
                  crossAxisCount: 2, // 一行的 Widget 的数量
                ),

                itemCount: tabList.length,
                itemBuilder: this._getListData, // 直接返回Widget
              )
            : Container(),
        (this.tabList.length <= 0 && !noDataflag && !errorFlag)
            ? _getMoreWidget()
            : Container(),
        noDataflag ? NoDataView() : Container(),
        errorFlag ? ErrorView() : Container(),

//        Container(
//          margin: EdgeInsets.only(top: TLSizeFit.setPx(220)),
//          child: Text("临时显示注册id:$Rid"),
//        ),
      ],
    );
  }

  Widget _getListData(context, index) {
    return InkWell(
      child: Container(
        height: TLSizeFit.setPx(120),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ClipOval(
              // 圆形头像
              // 设置头像
              child: Image.asset(
                this.imageList[index],
                width: TLSizeFit.setPx(50),
                height: TLSizeFit.setPx(50),
                // 设置图片的缩放模式
                fit: BoxFit.cover,
              ),
            ),
            SizedBox(
              width: TLSizeFit.setPx(10),
            ),
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  tabList[index],
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 14, color: YColors.c),
                )
              ],
            ),
          ],
        ),
        decoration: BoxDecoration(
//          border:
//              Border.all(color: Color.fromRGBO(233, 233, 233, 0.9), width: 1),
          color: YColors.t,
          borderRadius: BorderRadius.all(Radius.circular(4)), // 圆角 zj)
        ),
      ),
      onTap: () {
        print("点击了事件级${tabList[index]}");

        if (tabList[index] == null) {
          return;
        }
        switch (tabList[index]) {
          case "待办任务":
            Navigator.pushNamed(context, "/waitDoTaskPage"); //   WaitDoTaskPage
            break;
          case "历史任务":
            Navigator.pushNamed(context, "/historyTaskPage");
            break;
          case "办结任务":
            Navigator.pushNamed(context, "/finishTaskPage");
            break;
          case "我发起的":
            Navigator.pushNamed(context, "/launchTaskPage");
            break;
        }
      },
    );
  }

  //加载中的圈圈
  Widget _getMoreWidget() {
    if (hasMore) {
      return Center(
        child: Padding(
          padding: EdgeInsets.all(10.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text(
                '加载中',
                style: TextStyle(fontSize: 16.0),
              ),
              SizedBox(width: 10),
              CircularProgressIndicator(
                strokeWidth: 1.0,
              )
            ],
          ),
        ),
      );
    } else {
      return Center(
        child: Text(""),
      );
    }
  }

  /**
   * 给后台提交极光的注册id
   */
  httpJPushRegistrationID(registId) async {
    setState(() {
      Rid = registId;
    });
    Storage.setString(Global.JPUSHREGISTERID, registId);

    String registState = await Storage.getString(Global.JPUSHREGISTERSTATE);
    LogUtil.v("极光registState:$registState");

    if (registState != null && registState == "1") {
      LogUtil.v("极光已注册过，不需要再次注册");
      return;
    }

    String url = GlobalUrl.JPUSHUPDATEBINDSTATUS;
    var map = {
      "registrationId": registId,
      "validFlag": "1", //1 登录 0 退出
    };
    String access_token = await Storage.getToken();
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };

    HttpUtil.post(url, context: this.context, data: map, headers: mapHeaders,
        success: (data) {
      LogUtil.v("极光的注册success:$data");
//          极光的注册success:{code: 200, success: true, data: null, msg: 操作成功}
      var jsonMap = BossBean.fromJson(data);
      String result = jsonMap.code;
      String message = jsonMap.msg;
      bool success = jsonMap.success;
      if (success) {
        Storage.setString(Global.JPUSHREGISTERSTATE, "1");
      } else {
        ToastUtils.toast(message);
      }
//          ToastUtils.toast(message);
    }, error: (error) {
      LogUtil.v("极光的注册error:$error");
    });
  }
}
